//
//  AddUserViewController.m
//  Riese
//
//  Created by air on 2019/10/20.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "AddUserViewController.h"
#import "QFDatePickerView.h"
#import <MMAlertView.h>
#import <TPKeyboardAvoidingScrollView.h>

#import "HistoryViewController.h"

@interface AddUserViewController () <UIPickerViewDelegate,UIPickerViewDataSource, UIImagePickerControllerDelegate, UITextFieldDelegate> {
    UITextField *tf;
    UIButton * btn_sexM;
    UIButton * btn_sexF;
    UIButton * btn_ImgV;
    UIImageView *avatar;
    NSData *avataImageData;
}

@property (nonatomic, strong) TPKeyboardAvoidingScrollView *scroll;

@property (nonatomic, strong) FMDatabase *db;

// 年龄
@property(nonatomic,strong) UIPickerView *pickerView;
@property (nonatomic,strong) NSMutableArray *yearArray;
@property (nonatomic,assign) BOOL isLeapyear;//是否是闰年

// 头像
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@property (nonatomic) NSUInteger sourceType;
@property (nonatomic, strong) UIPopoverController *popoverController;

@end

@implementation AddUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromHex(0xF3F3F3);
    self.navigationItem.title = NSLocalizedString(@"Add User", nil);
    
    self.yearArray = [NSMutableArray arrayWithCapacity:0];
    [self makeUI];
}

- (void)makeUI {
    self.scroll = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarAndStatusBarHeight)];
    self.scroll.showsVerticalScrollIndicator = NO;
    self.scroll.contentSize = CGSizeMake(SCREEN_WIDTH, 610);
    [self.view addSubview:self.scroll];
    
    btn_ImgV = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.scroll addSubview:btn_ImgV];
    
    btn_ImgV.sd_layout.leftSpaceToView(self.scroll, SCREEN_WIDTH / 2 - 57).topSpaceToView(self.scroll, 10).widthIs(114).heightIs(114);
    [btn_ImgV setBackgroundImage:[UIImage imageNamed:@"addUser_icon"] forState:UIControlStateNormal];
    [btn_ImgV addTarget:self action:@selector(btnImgVClick) forControlEvents:UIControlEventTouchUpInside];
    
    avatar = [[UIImageView alloc] initWithFrame:CGRectMake(13, 1, 88, 88)];
    avatar.layer.cornerRadius = 44;
    avatar.clipsToBounds = YES;
    [btn_ImgV addSubview:avatar];
    
    UILabel * lab_nickname = [[UILabel alloc] init];
    [self.scroll addSubview:lab_nickname];
    lab_nickname.textColor = UIColorFromHex(0x666666);
//    lab_nickname.backgroundColor =[UIColor blueColor];
    lab_nickname.sd_layout.leftSpaceToView(self.scroll, 25).topSpaceToView(btn_ImgV, 0).widthIs(100).heightIs(20);
    lab_nickname.text = NSLocalizedString(@"Nickname", nil);
    
    tf = [[UITextField alloc] init];//WithFrame:CGRectMake(10, 100, SCREEN_WIDTH - 20, 30)];
    tf.placeholder = @"   Please enter your name";
    tf.delegate = self;
    [self.scroll addSubview:tf];
    tf.sd_layout.leftEqualToView(lab_nickname).topSpaceToView(lab_nickname, 10).widthIs(SCREEN_WIDTH - 2 * 25).heightIs(50);
    tf.backgroundColor = [UIColor whiteColor];
    tf.layer.cornerRadius = tf.height / 2;
    tf.returnKeyType = UIReturnKeyDone;
    tf.clipsToBounds = YES;
    [tf setValue:[NSNumber numberWithInt:2] forKey:@"paddingTop"];
    [tf setValue:[NSNumber numberWithInt:15] forKey:@"paddingLeft"];
    [tf setValue:[NSNumber numberWithInt:2] forKey:@"paddingBottom"];
    [tf setValue:[NSNumber numberWithInt:15] forKey:@"paddingRight"];
    
    UILabel * lab_sex = [[UILabel alloc] init];
    [self.scroll addSubview:lab_sex];
    lab_sex.textColor = UIColorFromHex(0x666666);
    lab_sex.sd_layout.leftEqualToView(lab_nickname).topSpaceToView(tf, 10).widthIs(100).heightIs(20);
    lab_sex.text = NSLocalizedString(@"Sex", nil);
    
    UIView * v_sexBg = [[UIView alloc] init];
    [self.scroll addSubview:v_sexBg];
    v_sexBg.sd_layout.leftEqualToView(lab_sex).topSpaceToView(lab_sex, 10).widthIs(tf.width).heightIs(50);
    v_sexBg.layer.cornerRadius = v_sexBg.height / 2;
    v_sexBg.clipsToBounds = YES;
    
    btn_sexM = [UIButton buttonWithType:UIButtonTypeCustom];
    [v_sexBg addSubview:btn_sexM];
    [btn_sexM setBackgroundColor:[UIColor whiteColor]];
    [btn_sexM setSelected:YES];
    btn_sexM.sd_layout.leftSpaceToView(v_sexBg, 0).topSpaceToView(v_sexBg, 0).widthIs(v_sexBg.width / 2).heightIs(v_sexBg.height);
    [btn_sexM setTitle:NSLocalizedString(@"Male", nil) forState:UIControlStateNormal];
    [btn_sexM setTitleColor:UIColorFromHex(0x5CBBC0) forState:UIControlStateNormal];
    btn_sexM.tag = 210;
    [btn_sexM addTarget:self action:@selector(sexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    btn_sexF = [UIButton buttonWithType:UIButtonTypeCustom];
    [v_sexBg addSubview:btn_sexF];
    
    btn_sexF.sd_layout.leftSpaceToView(btn_sexM, 0).topEqualToView(btn_sexM).widthIs(v_sexBg.width / 2).heightIs(v_sexBg.height);
    [btn_sexF setBackgroundColor:UIColorFromHex(0xE1E1E1)];
    [btn_sexF setSelected:NO];
    [btn_sexF setTitle:NSLocalizedString(@"Female", nil) forState:UIControlStateNormal];
    [btn_sexF setTitleColor:UIColorFromHex(0x666666) forState:UIControlStateNormal];
    btn_sexF.tag = 211;
    [btn_sexF addTarget:self action:@selector(sexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel * lab_age = [[UILabel alloc] init];
    [self.scroll addSubview:lab_age];
    lab_age.textColor = UIColorFromHex(0x666666);
    lab_age.sd_layout.leftEqualToView(lab_nickname).topSpaceToView(v_sexBg, 10).widthIs(100).heightIs(20);
    lab_age.text = NSLocalizedString(@"Age", nil);
    
    
    //时间选择器
    self.pickerView = [UIPickerView new];
    self.pickerView.backgroundColor = [UIColor whiteColor];
    self.pickerView.tintColor = kColor(51, 51, 51);
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.scroll addSubview:self.pickerView];
    self.pickerView.sd_layout.leftSpaceToView(self.scroll, 20).rightSpaceToView(self.scroll, 10).topSpaceToView(lab_age, 10).heightIs(154);
    
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy"];
    NSString *thisYearString=[dateformatter stringFromDate:senddate];
    
    for (int i = [thisYearString intValue]; i >= 1900; i--) {
        [self.yearArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    NSString *rowValue = [self.isEdit integerValue] == 1 ? self.dataDic[@"age"] : thisYearString;
    for (int i = 0; i < self.yearArray.count; i++) {
        if ([self.yearArray[i] isEqualToString:rowValue]) {
            [self.pickerView selectRow:i inComponent:0 animated:NO];
        }
    }
    
    [self.pickerView reloadAllComponents];
    
    if ([self.isEdit isEqualToString:@"0"]) {
        // 添加用户
        UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.scroll addSubview:saveBtn];
        saveBtn.sd_layout.leftSpaceToView(self.scroll, 20).topSpaceToView(self.pickerView, 25).widthIs(SCREEN_WIDTH - 20 * 2).heightIs(50);//.frame = CGRectMake(10, 150, SCREEN_WIDTH - 20, 40);
        [saveBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
        [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [saveBtn setBackgroundColor:UIColorFromHex(0x5CBBC0)];
        saveBtn.layer.cornerRadius = saveBtn.height / 2;
        //    saveBtn.clipsToBounds = YES;
        
        saveBtn.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2].CGColor;
        saveBtn.layer.shadowOffset = CGSizeMake(0,8);
        saveBtn.layer.shadowOpacity = 1;
        saveBtn.layer.shadowRadius = 10;
    }
    else {
        // 修改用户信息
        UIButton *historyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        historyBtn.backgroundColor = [UIColor clearColor];
        [historyBtn addTarget:self action:@selector(historyBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.scroll addSubview:historyBtn];
        historyBtn.sd_layout.leftSpaceToView(self.scroll, 0).rightSpaceToView(self.scroll, 0).topSpaceToView(self.pickerView, 0).heightIs(45);
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = NSLocalizedString(@"Historical cases", nil);
        titleLabel.textColor = kColor(51, 51, 51);
        titleLabel.font = kRegularFont(16);
        [historyBtn addSubview:titleLabel];
        titleLabel.sd_layout.leftSpaceToView(historyBtn, 25).topSpaceToView(historyBtn, 0).heightIs(45);
        [titleLabel setSingleLineAutoResizeWithMaxWidth:0];
        
        UIImageView *arrow = [UIImageView new];
        arrow.image = [UIImage imageNamed:@"arrow_right"];
        [historyBtn addSubview:arrow];
        arrow.sd_layout.rightSpaceToView(historyBtn, 20).topSpaceToView(historyBtn, 15).widthIs(8).heightIs(15);
        
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.backgroundColor = [UIColor whiteColor];
        [deleteBtn setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
        [deleteBtn setTitleColor:kColor(208, 2, 27) forState:UIControlStateNormal];
        deleteBtn.titleLabel.font = kRegularFont(18);
        [self.scroll addSubview:deleteBtn];
        deleteBtn.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2].CGColor;
        deleteBtn.layer.shadowOffset = CGSizeMake(0,8);
        deleteBtn.layer.shadowOpacity = 1;
        deleteBtn.layer.shadowRadius = 10;
        deleteBtn.layer.cornerRadius = 25;
        [deleteBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
        deleteBtn.sd_layout.leftSpaceToView(self.scroll, 20).topSpaceToView(historyBtn, 0).widthIs(120).heightIs(50);
        
        UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [saveBtn setBackgroundColor:UIColorFromHex(0x5CBBC0)];
        [saveBtn setTitle:NSLocalizedString(@"Save change", nil) forState:UIControlStateNormal];
        [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        saveBtn.titleLabel.font = kRegularFont(18);
        [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
        saveBtn.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2].CGColor;
        saveBtn.layer.shadowOffset = CGSizeMake(0,8);
        saveBtn.layer.shadowOpacity = 1;
        saveBtn.layer.shadowRadius = 10;
        saveBtn.layer.cornerRadius = 25;
        [self.scroll addSubview:saveBtn];
        saveBtn.sd_layout.leftSpaceToView(deleteBtn, 15).rightSpaceToView(self.scroll, 20).topSpaceToView(historyBtn, 0).heightIs(50);
    }
    
    if ([self.isEdit isEqualToString:@"1"]) {
        tf.text = self.dataDic[@"nickname"];
        if ([self.dataDic[@"sex"] integerValue] == 0) {
            [btn_sexM setSelected:YES];
            [btn_sexF setSelected:NO];
        }
        else {
            [btn_sexM setSelected:NO];
            [btn_sexF setSelected:YES];
        }
        
        [btn_sexM setBackgroundColor:btn_sexM.isSelected ? [UIColor whiteColor] : UIColorFromHex(0xE1E1E1)];
        [btn_sexM setTitleColor:btn_sexM.isSelected ? UIColorFromHex(0x5CBBC0) : UIColorFromHex(0x666666) forState:UIControlStateNormal];
        
        [btn_sexF setBackgroundColor:btn_sexF.isSelected ? [UIColor whiteColor] : UIColorFromHex(0xE1E1E1)];
        [btn_sexF setTitleColor:btn_sexF.isSelected ? UIColorFromHex(0x5CBBC0) : UIColorFromHex(0x666666) forState:UIControlStateNormal];
        
        if ([self.dataDic[@"avatar"] length] > 0) {
            NSData *data = defaults(self.dataDic[@"avatar"]);
            avatar.image= [UIImage imageWithData:data];
        }
        else {
            avatar.image = nil;
        }
    }
}

#pragma mark - textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark --  UIPickerViewDataSource

/**
 *  返回有几个PickerView
 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
            
    return self.yearArray.count;
    
}

#pragma mark --  UIPickerViewDelegate

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
        if ((row+1900)%4==0) {
            self.isLeapyear = YES;
        }
        
        return [self.yearArray objectAtIndex:row];

}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 35.0;
}

#pragma mark - Button Click
- (void)historyBtnClick {
    HistoryViewController *vc = [HistoryViewController new];
    vc.avatarImg = avatar.image;
    vc.nickname = tf.text;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)btnImgVClick{
    [self choseImageV];
}

-(void)choseImageV{
    //这个里面选择头像 在选择完之后并保存头像到该用户下的本地
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            return;
        }
        self.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self photo];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self photo];
    }];
    
    [actionSheet addAction:action1];
    [actionSheet addAction:action2];
    [actionSheet addAction:action3];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

// 修改头像
- (void)photo {
    self.imagePickerController = [[UIImagePickerController alloc] init];
    self.imagePickerController.delegate = self;
    self.imagePickerController.allowsEditing = YES;
    self.imagePickerController.sourceType = self.sourceType;
    
    if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:self.imagePickerController];
        self.popoverController = popover;
        [self.popoverController presentPopoverFromRect:CGRectMake(0, 0, 300, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    else
    {
        [self presentViewController:self.imagePickerController animated:YES completion:^{}];
    }
}

//压缩图片
- (UIImage *)zipImage:(UIImage *)image{
    
    NSUInteger length = UIImageJPEGRepresentation(image,1).length;
    UIImage *imageTemp = [UIImage imageWithData:UIImageJPEGRepresentation(image, 0.1)];
    NSUInteger length2 = UIImageJPEGRepresentation(imageTemp,1).length;
    imageTemp = [self imageWithImage:imageTemp scaledToSize:CGSizeMake(imageTemp.size.width*0.5, imageTemp.size.height*0.5)];
    NSUInteger length3 = UIImageJPEGRepresentation(imageTemp,1).length;
    if (UIImageJPEGRepresentation(imageTemp,1).length > 100*1024) {
        NSLog(@"压缩图片");
        return [self zipImage:imageTemp];
    }else{
        return imageTemp;
    }
}

//裁剪图片
- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark 修改头像
#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    //    image = [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    avataImageData = UIImageJPEGRepresentation([self zipImage:image], 1.0);
    avatar.image = image;
}

-(void) sexBtnClick:(UIButton *)sender{
    if (sender.tag == 210) {
        [btn_sexM setSelected:YES];
        [btn_sexF setSelected:NO];
        
    }else if (sender.tag == 211){
        [btn_sexF setSelected:YES];
        [btn_sexM setSelected:NO];
    }
    [btn_sexM setBackgroundColor:btn_sexM.isSelected ? [UIColor whiteColor] : UIColorFromHex(0xE1E1E1)];
    [btn_sexM setTitleColor:btn_sexM.isSelected ? UIColorFromHex(0x5CBBC0) : UIColorFromHex(0x666666) forState:UIControlStateNormal];
    
    [btn_sexF setBackgroundColor:btn_sexF.isSelected ? [UIColor whiteColor] : UIColorFromHex(0xE1E1E1)];
    [btn_sexF setTitleColor:btn_sexF.isSelected ? UIColorFromHex(0x5CBBC0) : UIColorFromHex(0x666666) forState:UIControlStateNormal];
}

// 添加, 修改用户
- (void)saveBtnClick {
    if (tf.text.length == 0) {
        [YJProgressHUD showMessage:@"请输入昵称" inView:self.view];
    }
    else {
        // 创建数据库对象
        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString * path = [docsdir stringByAppendingPathComponent:@"UserInfo.sqlite"];//将需要创建的串拼接到后面
        self.db = [FMDatabase databaseWithPath:path];
        // 建表
        [self createTable:@"1"];
    }
}

- (void)deleteBtnClick {
    // 创建数据库对象
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * path = [docsdir stringByAppendingPathComponent:@"UserInfo.sqlite"];//将需要创建的串拼接到后面
    self.db = [FMDatabase databaseWithPath:path];
    // 建表
    [self createTable:@"2"];
}

#pragma mark - FMDB
// 创建表
- (void)createTable:(NSString *)type {

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"userInfo"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT,'avatar' 'text', 'nickname' 'text', 'sex' 'text','age' 'text');"];
           if (result) {
               if ([type integerValue] == 1) {
                   if ([self.isEdit isEqualToString:@"1"]) {
                       // 更新用户
                       [self updateUserInfo];
                   }
                   else {
                       // 插入用户
                       [self addUserInfo];
                   }
               }
               else {
                   [self deleteUserInfo];
               }
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           if ([type integerValue] == 1) {
               [self.db close];
           }
       }
       else {
           if ([type integerValue] == 1) {
               if ([self.isEdit isEqualToString:@"1"]) {
                   [self updateUserInfo];
               }
               else {
                   [self addUserInfo];
               }
           }
           else {
               [self deleteUserInfo];
           }
           if ([type integerValue] == 1) {
               [self.db close];
           }
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 删除数据
- (void)deleteUserInfo {
    NSArray *items = @[MMItemMake(NSLocalizedString(@"cancel", nil), MMItemTypeNormal, nil), MMItemMake(NSLocalizedString(@"sure", nil), MMItemTypeNormal, ^(NSInteger index) {
        // 删除数据
        NSString *sql = [NSString stringWithFormat:@"delete from UserInfo where ID = '%@'", self.dataDic[@"id"]];
        //删除
        if ([self.db executeUpdate:sql]) {
            NSLog(@"删除成功！");
            if ([self.dataDic[@"id"] isEqual:defaults(@"id")]) {
                removeDefaults(@"id");
                removeDefaults(@"avatar");
                removeDefaults(@"nickname");
                removeDefaults(@"sex");
                removeDefaults(@"age");
            }
            [self.db close];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUser" object:nil];
            [YJProgressHUD showMessage:NSLocalizedString(@"Delete successfully", nil) inView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else{
            [YJProgressHUD showMessage:NSLocalizedString(@"Delete failed", nil) inView:self.view];
        }
    })];
    [[[MMAlertView alloc] initWithTitle:@"" detail:[NSString stringWithFormat:@"\n%@", NSLocalizedString(@"Are you sure to delete?", nil)] items:items] show];
}

// 更新数据
- (void)updateUserInfo {
    NSString*timeString = @"";
    if (avataImageData) {
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970];
        timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
        
        setDefaults(avataImageData, timeString);
    }
    else {
        timeString = self.dataDic[@"avatar"];
    }
    
    //1.准备sqlite语句
    // sex: 0 male, 1 female
    NSString *sex = btn_sexM.isSelected ? @"0" : @"1";
    NSInteger row = [self.pickerView selectedRowInComponent:0];
    NSString *sqlite = [NSString stringWithFormat:@"update userInfo set avatar = '%@',nickname = '%@',sex = '%@',age = '%@' where ID = '%@'", timeString, tf.text, sex, self.yearArray[row], self.dataDic[@"id"]];
    //2.执行sqlite语句
    //    char *error = NULL;//执行sqlite语句失败的时候,会把失败的原因存储到里面
    BOOL result = [self.db executeUpdate:sqlite];
    if (result) {
        NSLog(@"更新数据成功");
        if ([defaults(@"id") isEqual:self.dataDic[@"id"]]) {
            setDefaults(timeString, @"avatar");
            setDefaults(tf.text, @"nickname");
            setDefaults(sex, @"sex");
            setDefaults(self.yearArray[row], @"age");
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUser" object:nil];
        [YJProgressHUD showMessage:NSLocalizedString(@"Save successfully", nil) inView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        
    } else {
        NSLog(@"更新数据失败");
        [YJProgressHUD showMessage:NSLocalizedString(@"Save failed", nil) inView:self.view];
    }
}

// 插入数据
- (void)addUserInfo {
    NSString*timeString = @"";
    if (avataImageData) {
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970];
        timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
        
        setDefaults(avataImageData, timeString);
    }
    
    //1.准备sqlite语句
    // sex: 0 male, 1 female
    NSString *sex = btn_sexM.isSelected ? @"0" : @"1";
    NSInteger row = [self.pickerView selectedRowInComponent:0];
    NSString *sqlite = [NSString stringWithFormat:@"insert into userInfo(avatar,nickname,sex,age) values ('%@','%@','%@','%@')", timeString, tf.text, sex, self.yearArray[row]];
    //2.执行sqlite语句
    //    char *error = NULL;//执行sqlite语句失败的时候,会把失败的原因存储到里面
    BOOL result = [self.db executeUpdate:sqlite];
    if (result) {
        NSLog(@"添加数据成功");
        [YJProgressHUD showMessage:NSLocalizedString(@"Save successfully", nil) inView:self.view];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUser" object:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } else {
        NSLog(@"添加数据失败");
        [YJProgressHUD showMessage:NSLocalizedString(@"Save failed", nil) inView:self.view];
    }
}

/**
 判断一张表是否已经存在
 @param tablename 表名
 */
- (BOOL)isExistTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM sqlite_master where type= 'table' and name= '%@';",tablename];
    FMResultSet *rs = [self.db executeQuery:sql];
//    BOOL result = [db executeQuery:sql];
    while ([rs next]) {
        NSInteger count = [rs intForColumnIndex:0];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
